<template>
    <div class="cmd-log">
        <div class="top-view">
            <div class="tit">
                <div v-for="(item, index) in deviceStore.clickedDevice" :key="index"
                    :class="{ 'deviceHighligt': highlightedIndex === index }" @click.stop="highlightItem(index)">
                    <input :id="String(index)" type="radio" name="tab-radio" class="tab-radio" checked>
                    <label :for="String(index)" class="tab-handler">
                        <span>
                            {{ item.name }}
                        </span>
                        <span>
                            <el-icon>
                                <Close @click.stop="closeCurrentTab(item)" />
                            </el-icon>
                        </span>
                    </label>

                </div>
            </div>
            <div class="toolbar">
                <el-tooltip placement="top-start" content="清除日志">
                    <el-icon>
                        <Delete @click="clearLog" />
                    </el-icon>
                </el-tooltip>
                <el-tooltip placement="top-start" content="导出日志">
                    <el-icon>
                        <Download @click="downloadLogFile" />
                    </el-icon>
                </el-tooltip>
            </div>
        </div>
        <div class="body-view">
            <div class="seacher">
                <el-input v-model="searchInfo" placeholder="请输入关键字" :suffix-icon="Search" clearable
                    @change="searchCmdInfo">
                </el-input>
            </div>
            <span v-if="showErMsg" class="errMsg">未检索到指定内容</span>
            <DataContainer ref="dataContainer" :initProps="JSON.stringify(dataContainerInit)"
                :dataList="JSON.stringify(dataContainerStruct)" :dataSingle="JSON.stringify(dataContainerStructSingle)"
                @callback="callback">
            </DataContainer>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { v4 as uuidv4 } from "uuid";
import moment from "moment";
import DataContainer from "../../DataContainer/DataContainer.vue";
import type { DataStruct, PaginagedData } from "../../DataContainer/DataContainer";
import { Delete, Download, Close } from "@element-plus/icons-vue";
import { sendCommand, downloadFileCommand } from "../../api/manualTest/index"
import { ElMessage } from "element-plus";
import { Search } from '@element-plus/icons-vue';

import { useDeviceStore } from "../../store/deviceView";

const deviceStore = useDeviceStore();

defineOptions({
    name: "CmdEnforcement",
});

// Props
const props = defineProps({
    manualTestLog: {
        type: String,
        default: "",
    },
});

const dataContainer = ref(null);

// Reactive state
const highlightedIndex = ref(0);
const dataContainerStruct = ref<DataStruct[]>([]);
const dataContainerStructSingle = ref<DataStruct>({
    Id: "",
    Content: "",
});
const searchInfo = ref("");
const showErMsg = ref(false);
const effect = ref("light");
const pageObj = reactive({
    currentIndex: 1,
    pageSize: 100,
    totalDataCount: 0,
});
const dataContainerInit = ref({
    paginatedData: pageObj,
    isBottomScroll: false,
    isHtml: true,
});

const getAllCount = async () => {

    if (!deviceStore.currentDevice?.id) return;

    const testResult = await sendCommand(
        { deviceId: deviceStore.currentDevice?.id },
        { commandName: "GetManualTestLogsCount" }
    );

    const { data } = testResult as { data: number };

    pageObj.totalDataCount = data;
};

// Watchers
watch(
    () => deviceStore.currentDevice?.id,
    async (val: string | undefined) => {
        if (!val) return;

        dataContainerStruct.value = [];

        highlightedIndex.value = deviceStore.clickedDevice.findIndex((childItem: any) => childItem.id === val);

        console.log("获取总条数");
        await getAllCount();

        await getHistoryLogByPage();

        if (dataContainerStruct.value.length < pageObj.pageSize) {
            pageObj.currentIndex--;
            await getHistoryLogByPage();
        }
    },
    {
        immediate: true
    }
);

watch(() => deviceStore.clickedDevice.length,
    (val) => {
        if (val === 0) {
            dataContainerStruct.value = [];
            highlightedIndex.value = 0;
        }
    });

watch(
    () => props.manualTestLog,
    async () => {

        const obj = JSON.parse(props.manualTestLog);

        const opeContent = obj.content.replace(/\r\n/g, "<br>");
        const format = "HH:mm:ss.SSS";
        const judge = moment(obj.dateTime, format, true).isValid();
        if (!judge) {
            obj.dateTime = moment(obj.dateTime).format("HH:mm:ss.SSS");
        }

        dataContainerStructSingle.value = {
            Id: uuidv4(),
            Content: `${obj.dateTime} ${obj.actionType} ${opeContent}`,
        };

        // await getAllCount();
        pageObj.totalDataCount++;
    }
);

watch(
    () => highlightedIndex.value,
    () => {
        dataContainerStruct.value = [];
    }
);

watch(
    () => pageObj.totalDataCount,
    () => {
        const totalPage = Math.ceil(pageObj.totalDataCount / pageObj.pageSize);
        pageObj.currentIndex = totalPage;
    }
);

// Methods
const highlightItem = (index: number) => {
    highlightedIndex.value = index;
    if (deviceStore.clickedDevice.length > index) {
        deviceStore.setCurrentDevice(deviceStore.clickedDevice[index]);
    }
};

const closeCurrentTab = (ele: any) => {
    deviceStore.removeClickedDevice(ele);
    if (deviceStore.allDevices.length !== 0) {
        deviceStore.setCurrentDevice(deviceStore.allDevices[0]);
    }
    dataContainerStruct.value = [];
    deviceStore.setClosedDevice(ele);
};

const clearLog = async () => {
    dataContainerStruct.value = [];

    await sendCommand(
        { deviceId: deviceStore.currentDevice?.id },
        { commandName: "ClearLogs" }
    );

    ElMessage.success("日志清除成功");
    console.log("clearLog");
};

const downloadLogFile = async () => {

    const blob = await downloadFileCommand(
        { deviceId: deviceStore.currentDevice?.id },
        { commandName: "GetLogFile" },
        { responseType: "blob" }
    );
    console.log("获取日志文件", blob);
    // const data = blob as Blob;
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob as any);
    link.href = url;
    link.download = `${deviceStore.currentDevice?.name}-${deviceStore.currentDevice?.version}.log`;
    link.click();
    URL.revokeObjectURL(url);
};

const searchCmdInfo = () => {
    (dataContainer.value as any)?.searchInfo(searchInfo.value);
};

const getHistoryLogByPage = async () => {

    const testResult = await sendCommand(
        {
            deviceId: deviceStore.currentDevice?.id,
            pageIndex: pageObj.currentIndex,
            pageSize: pageObj.pageSize
        },
        { commandName: "GetManualTestLogsByPage" }
    );

    const { data } = testResult as { data: { list: string[] } };

    if (data && data.list?.length) {
        // dataContainerStruct.value = [];
        const tempLogList = data.list.map((log: string) => ({
            Id: uuidv4(),
            Content: log.replace(/\r\n/g, "<br>"),
        }));
        dataContainerStruct.value = [...tempLogList, ...dataContainerStruct.value];
    }

};

// Lifecycle hooks
onMounted(async () => {
    const currentTheme = localStorage.getItem("theme");
    if (currentTheme) {
        effect.value = "dark";
    }

});

const callback = async (data: PaginagedData) => {
    Object.assign(pageObj, data);

    await getHistoryLogByPage();
}


</script>

<style scoped lang="scss">
.cmd-log {
    height: calc(100% - 10px);
    // display: flex;
    // flex-direction: column;

    .top-view {
        display: flex;
        justify-content: space-between;
        height: 30px;
        background-color: #dddddd;
        font-size: 12px;
        color: #666666;
        font-weight: 500;
        display: flex;
        align-items: center;
        padding-left: 12px;

        .tit {
            display: flex;
            justify-content: space-between;

            .tab-radio {
                display: none;
            }
        }

        .toolbar {
            margin-right: 15px;

            :deep(i) {
                cursor: pointer;
                padding-left: 10px;
                font-size: 15px;
            }
        }
    }

    .errMsg {
        color: red;
        text-align: right;
    }

    .body-view {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: calc(100% - 30px);
        border-bottom: 1px solid #dddddd;
        // overflow: hidden;

        .null-box {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #909399;
            font-size: 12px;
        }

        :deep(.seacher) {
            box-sizing: border-box;
            margin: 4px 2px;
            height: 30px;

            .el-input__wrapper {
                background-color: #f3f3f3;
                border: 1px solid #e4e7ed;
                box-sizing: border-box;
            }

            :deep(.el-input__inner) {
                height: 30px;
                line-height: 30px;
                background-color: #f3f3f3 !important;
                color: #666666 !important;
            }

            :deep(.el-input__inner::placeholder) {
                color: #909399 !important;
                font-size: 12px !important;
            }

            :deep(.el-input__icon) {
                line-height: 30px;
            }
        }

        :deep(.el-scrollbar__wrap) {
            // border: 1px solid #ccc !important;
            max-height: 99%;
        }

        :deep(.highlight) {
            background-color: blue;
            color: white;
        }

        .editableDiv {
            color: #666666;
            padding: 10px;
            height: 100%;
            /* Example max-height to enable scrolling */
            // outline: none;
        }
    }

    .tab-wrapper {
        position: relative;
        width: 540px;
        height: 30px;
        background-color: #33344a;
    }

    .tab-wrapper .tab-radio {
        display: none;
    }

    .tab-handler {
        position: relative;
        z-index: 2;
        display: block;
        float: left;
        height: 28px;
        padding: 0 10px;
        color: #666666;
        font-size: 12px;
        line-height: 28px;
        cursor: pointer;

        span {
            padding-right: 5px
        }
    }

    .tab-radio:checked {
        visibility: visible;
        opacity: 1;
    }

    :deep(.deviceHighligt) {
        color: #666666;
        background-color: #fafafa;
        margin-bottom: -1px;
    }

}
</style>
